"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import Sidebar from "@/components/sidebar"
import { fetchUserProfile, updateUserProfile } from "@/lib/api"

export default function UserInfoPage() {
  const router = useRouter()
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [avatarPreview, setAvatarPreview] = useState("/images/profilePhoto.jpg")
  const [avatarFile, setAvatarFile] = useState<File | null>(null)
  const [formData, setFormData] = useState({
    email: "",
    realname: "",
    phone: "",
    password: "",
    confirmPassword: "",
  })
  const [errors, setErrors] = useState({
    realname: "",
    password: "",
    confirmPassword: "",
  })
  const [successMessage, setSuccessMessage] = useState("")

  useEffect(() => {
    const loadUserProfile = async () => {
      try {
        const profile = await fetchUserProfile()
        setFormData({
          ...formData,
          email: profile.email,
          realname: profile.realname || "",
          phone: profile.phone || "",
        })
        if (profile.avatar) {
          setAvatarPreview(profile.avatar)
        }
      } catch (error) {
        console.error("Failed to load user profile:", error)
      } finally {
        setLoading(false)
      }
    }

    loadUserProfile()
  }, [])

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData({
      ...formData,
      [name]: value,
    })

    // Clear errors when typing
    if (name in errors) {
      setErrors({
        ...errors,
        [name]: "",
      })
    }
  }

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setAvatarFile(file)
      const reader = new FileReader()
      reader.onload = () => {
        setAvatarPreview(reader.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  const validateForm = () => {
    let valid = true
    const newErrors = { ...errors }

    if (!formData.realname) {
      newErrors.realname = "请输入真实姓名"
      valid = false
    }

    if (formData.password && formData.password.length < 6) {
      newErrors.password = "密码长度至少为6个字符"
      valid = false
    }

    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = "两次输入的密码不一致"
      valid = false
    }

    setErrors(newErrors)
    return valid
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!validateForm()) {
      return
    }

    setSaving(true)
    setSuccessMessage("")

    try {
      await updateUserProfile({
        realname: formData.realname,
        phone: formData.phone,
        password: formData.password || undefined,
        avatar: avatarFile,
      })

      setSuccessMessage("个人信息更新成功！")
      // 清空密码字段
      setFormData({
        ...formData,
        password: "",
        confirmPassword: "",
      })
    } catch (error) {
      console.error("Failed to update profile:", error)
      setSuccessMessage("")
    } finally {
      setSaving(false)
    }
  }

  const clearForm = () => {
    setFormData({
      ...formData,
      realname: "",
      phone: "",
      password: "",
      confirmPassword: "",
    })
    setErrors({
      realname: "",
      password: "",
      confirmPassword: "",
    })
    setSuccessMessage("")
  }

  if (loading) {
    return (
      <div className="flex h-screen">
        <Sidebar />
        <div className="flex-1 p-8 flex items-center justify-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
        </div>
      </div>
    )
  }

  return (
    <div className="flex h-screen bg-gray-100">
      <Sidebar />

      <main className="flex-1 p-8 overflow-y-auto">
        <h2 className="text-3xl font-bold mb-6">个人信息维护</h2>

        {successMessage && <div className="mb-6 p-4 bg-green-100 text-green-700 rounded-md">{successMessage}</div>}

        <form className="space-y-6" onSubmit={handleSubmit}>
          {/* 头像设置 */}
          <div>
            <h3 className="text-2xl font-semibold mb-4">头像设置</h3>
            <div className="flex items-center space-x-4">
              <div className="relative w-24 h-24">
                <Image
                  src={avatarPreview || "/placeholder.svg"}
                  alt="用户头像"
                  fill
                  className="rounded-full object-cover"
                />
              </div>
              <div>
                <Label htmlFor="avatar" className="text-gray-600">
                  选择新头像
                </Label>
                <Input
                  type="file"
                  id="avatar"
                  accept="image/*"
                  onChange={handleAvatarChange}
                  className="mt-2 p-2 border border-gray-300 rounded-md"
                />
              </div>
            </div>
          </div>

          {/* 邮箱（置灰不可修改） */}
          <div>
            <Label htmlFor="email" className="block text-sm font-medium text-gray-700">
              邮箱
            </Label>
            <Input
              type="email"
              id="email"
              name="email"
              value={formData.email}
              className="mt-1 block w-full p-2 border border-gray-300 rounded-md bg-gray-200 cursor-not-allowed"
              disabled
            />
          </div>

          {/* 真实姓名 */}
          <div>
            <Label htmlFor="realname" className="block text-sm font-medium text-gray-700">
              真实姓名 <span className="text-red-500">*</span>
            </Label>
            <Input
              type="text"
              id="realname"
              name="realname"
              value={formData.realname}
              onChange={handleChange}
              className={`mt-1 block w-full p-2 border rounded-md ${
                errors.realname ? "border-red-500" : "border-gray-300"
              }`}
              placeholder="请输入真实姓名"
            />
            {errors.realname && <p className="mt-1 text-sm text-red-500">{errors.realname}</p>}
          </div>

          {/* 手机号 */}
          <div>
            <Label htmlFor="phone" className="block text-sm font-medium text-gray-700">
              手机号
            </Label>
            <Input
              type="tel"
              id="phone"
              name="phone"
              value={formData.phone}
              onChange={handleChange}
              className="mt-1 block w-full p-2 border border-gray-300 rounded-md"
              placeholder="请输入手机号"
            />
          </div>

          {/* 密码修改 */}
          <div>
            <Label htmlFor="password" className="block text-sm font-medium text-gray-700">
              新密码
            </Label>
            <Input
              type="password"
              id="password"
              name="password"
              value={formData.password}
              onChange={handleChange}
              className={`mt-1 block w-full p-2 border rounded-md ${
                errors.password ? "border-red-500" : "border-gray-300"
              }`}
              placeholder="请输入新密码（不修改请留空）"
            />
            {errors.password && <p className="mt-1 text-sm text-red-500">{errors.password}</p>}
          </div>

          <div>
            <Label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700">
              确认密码
            </Label>
            <Input
              type="password"
              id="confirmPassword"
              name="confirmPassword"
              value={formData.confirmPassword}
              onChange={handleChange}
              className={`mt-1 block w-full p-2 border rounded-md ${
                errors.confirmPassword ? "border-red-500" : "border-gray-300"
              }`}
              placeholder="确认新密码"
            />
            {errors.confirmPassword && <p className="mt-1 text-sm text-red-500">{errors.confirmPassword}</p>}
          </div>

          {/* 操作按钮 */}
          <div className="flex space-x-4 mt-6">
            <Button type="submit" className="w-full py-2 bg-primary text-white rounded-md" disabled={saving}>
              {saving ? "保存中..." : "确认修改"}
            </Button>
            <Button
              type="button"
              variant="outline"
              className="w-full py-2 bg-gray-300 text-gray-700 rounded-md"
              onClick={clearForm}
              disabled={saving}
            >
              清空内容
            </Button>
          </div>
        </form>
      </main>
    </div>
  )
}
